var DetailArticle   = {
    articleId:0,
    content:'',
    email:'',
    fullname:'',
    website:'',
    send_request:null,
    send_request_comment:null,
    redirect:0,
    commentId:0,
    strip_tags:function(input, allowed) {
        allowed = (((allowed || "") + "")
            .toLowerCase()
            .match(/<[a-z][a-z0-9]*>/g) || [])
        .join('');
        var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
        return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1){
            return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
        });
    },
    checkEmail:function(email) {
        var re = /^([A-Za-z0-9\_\-]+\.)*[A-Za-z0-9\_\-]+@[A-Za-z0-9\_\-]+(\.[A-Za-z0-9\_\-]+)+$/;
        if ( email.search(re) == -1 ) {
            return false;
        } else {
            return true;
        }
    },
    vote:function(id) {
        if ( DetailArticle.send_request != null ) {
            return false;
        }
        
        DetailArticle.send_request  = $.ajax({
            url:domain_url+'/index/vote',
            type:'POST',
            dataType:'json',
            data:({
                id:id
            }),
            success:function(response) {
                if ( response.error == 0 ) {
                    var $voteBlock1 = $("#voteblock1");
                    var $voteBlock2 = $("#voteblock2");
                    $voteBlock1.removeClass('but_binhchon').addClass('but_binhchon_none');
                    $voteBlock2.removeClass('but_binhchon').addClass('but_binhchon_none');
                    $("#buttonvote1").replaceWith('<a href="javascript:;">Bình chọn</a>');
                    $("#buttonvote2").replaceWith('<a href="javascript:;">Bình chọn</a>');
                    var $voteValue1 = $("#votevalue1");
                    var $voteValue2 = $("#votevalue2");
                    var currentVote = parseInt($voteValue1.text());
                    currentVote++;
                    $voteValue1.text(currentVote);
                    $voteValue2.text(currentVote);
                }
            },
            beforeSend:function() {
                
            },
            error:function() {
                
            },
            complete:function() {
                if ( DetailArticle.redirect ) {
                    DetailArticle.redirect  = 0;
                    window.location = window.location.href;
                }

                setTimeout(function(){
                    DetailArticle.send_request  = null;
                }, 500);
            }
        });
    },
    getComment:function(page) {
        if ( articleStatus == 1 ) {
            $.ajax({
                url:domain_url+'/index/getcomment',
                type:'GET',
                dataType:'json',
                data:({
                    id:articleId,
                    page:page
                }),
                success:function(response) {
                    if ( response.error == 0 ) {
                        $("#commentitem").html(response.html);
                        if ( response.paging != '' ) {
                            $("#pagingblock").html(response.paging).show();
                        }
                        setTimeout("FPT_widget_mix();", 100);
                    }
                },
                beforeSend:function() {

                },
                error:function() {

                },
                complete:function() {
                    
                }
            });
        }
    },
    comment:function(type) {
        /**
         * Check send request comment
         */
        if ( DetailArticle.send_request_comment != null ) {
            if ( type != 3 ) {
                alert("Bạn không được bình luận liên tục.");
            }
            return false;
        }

        /**
         * Type: 1-is login, 2-none login
         */
        if ( type == 1 ) {
            /**
             * Check content comment
             */
            var $content    = $("#txtComment");
            var content     = $.trim(DetailArticle.strip_tags($content.val()));
            $content.val(content);
            if ( content.length<=0 || content=='Ý kiến của bạn' ) {
                return false;
            }
            if ( content.length > 1000 ) {
                alert('Ý kiến của bạn không được phép vượt quá 1000 ký tự.');
                return false;
            }
            var email       = '';
            var fullname    = '';
            var website     = '';
        } else if ( type == 2 ) {
            var $content    = $("#txtComment");
            var content     = DetailArticle.content;
            var email       = DetailArticle.email;
            var fullname    = DetailArticle.fullname;
            var website     = DetailArticle.website;
        } else if ( type == 3 ) {
            var $content    = $("#txtComment");
            var content     = DetailArticle.content;
            var email       = '';
            var fullname    = '';
            var website     = '';
        }

        /**
         * Send request
         */
        DetailArticle.send_request_comment  = $.ajax({
            url:domain_url+'/index/comment',
            type:'POST',
            dataType:'json',
            data:({
                id:articleId,
                email:email,
                fullname:fullname,
                website:website,
                content:content
            }),
            success:function(response) {
                if ( response.error == 0 ) {
                    /**
                     * Get list comment
                     */
                    var $commentIteam   = $("#commentitem");
                    var htmlOld         = $commentIteam.html();
                    $commentIteam.html(response.html+htmlOld);

                    /**
                     * Set total coment on page
                     */
                    var $totalCommentBlock  = $("#totalcommentBlock");
                    var totalComment    = parseInt($totalCommentBlock.html());
                    totalComment++;
                    $totalCommentBlock.html(totalComment);

                    /**
                     * Call widget
                     */
                    setTimeout("FPT_widget_mix();", 100);
                } else if ( response.error == 3 ) {
                    alert("Bạn không được bình luận liên tục.");
                } else {
                    alert("Có lỗi xảy ra, vui lòng thực hiện lại sau.");
                }
            },
            beforeSend:function() {

            },
            error:function() {

            },
            complete:function() {
                if ( DetailArticle.redirect ) {
                    DetailArticle.redirect  = 0;
                    window.location = window.location.href;
                }
                $content.val('Ý kiến của bạn');
                DetailArticle.content   = '';
                DetailArticle.email     = '';
                DetailArticle.fullname  = '';
                setTimeout(function(){
                    DetailArticle.send_request_comment  = null;
                }, 10000);
            }
        });
    },
    deleteComment:function(commentId) {
        DetailArticle.commentId = commentId;
        /**
         * Show colorbox
         */
        jQuery.colorbox({width:"460px", inline:true, href:"#id_popup_del_comment"});
    },
    deleteCommentCallback:function() {
        if ( DetailArticle.send_request != null ) {
            return false;
        }

        /**
         * Send request
         */
        DetailArticle.send_request  = $.ajax({
            url:domain_url+'/index/deletecomment',
            type:'POST',
            dataType:'json',
            data:({
                id:articleId,
                commentId:DetailArticle.commentId
            }),
            success:function(response) {
                if ( response.error == 0 ) {
                    $("#commentItem-"+DetailArticle.commentId).fadeOut('slow', function(){
                        $(this).remove();
                    });
                } else {
                    alert("Có lỗi xảy ra, vui lòng thực hiện lại sau.");
                }
            },
            beforeSend:function() {
                jQuery.colorbox.close();
            },
            error:function() {
                
            },
            complete:function() {
                DetailArticle.commentId = 0;
                setTimeout(function(){
                    DetailArticle.send_request  = null;
                }, 500);
            }
        });
    },
    cancelDeleteComment:function() {
        jQuery.colorbox.close();
    },
    sendVoteWith:function() {
        /**
         * Show colorbox
         */
        jQuery.colorbox({width:"560px", inline:true, href:"#id_popup_login_vote"});
        /**
         * Set iframe login
         */
        DetailArticle.setIFrameFptId('a11', 2);
    },
    sendCommentWith:function() {
        /**
         * Check send request comment
         */
        if ( DetailArticle.send_request_comment != null ) {
            alert("Bạn không được bình luận liên tục.");
            return false;
        }

        /**
         * Check content comment
         */
        var $content    = $("#txtComment");
        var content     = $.trim(DetailArticle.strip_tags($content.val()));
        $content.val(content);
        if ( content.length<=0 || content=='Ý kiến của bạn' ) {
            return false;
        }
        if ( content.length > 1000 ) {
            alert('Ý kiến của bạn không được phép vượt quá 1000 ký tự.');
            return false;
        }

        /**
         * Set data
         */
        DetailArticle.content   = content;

        /**
         * Show colorbox
         */
        jQuery.colorbox({width:"560px", inline:true, href:"#id_popup_login"});
    },
    sendCommentGuest:function(id) {
        /**
         * Check email & fullname
         */
        var error           = 0;
        var $email          = $("#emailGuest");
        var email           = $.trim($email.val());
        var $fullname       = $("#fullnameGuest");
        var fullname        = $.trim(DetailArticle.strip_tags($fullname.val()));
        var $emailErr       = $("#errGuestEmail");
        var $fullnameErr    = $("#errGuestFullName");
        $email.val(email);
        $fullname.val(fullname);

        /**
         * Check data
         */
        if ( email.length <= 0 ) {
            $emailErr.html('<br>Vui lòng nhập email').show();
            error   = 1;
        } else if ( !DetailArticle.checkEmail(email) ) {
            $emailErr.html('<br>Email không hợp lệ').show();
            error   = 1;
        } else {
            $emailErr.html('').hide();
        }
        if ( fullname.length <= 0 ) {
            $fullnameErr.html('<br>Vui lòng nhập họ tên').show();
            error   = 1;
        } else {
            $fullnameErr.html('').hide();
        }
        if ( !error ) {
            DetailArticle.email     = email;
            DetailArticle.fullname  = fullname;
            jQuery.colorbox.close();
            DetailArticle.comment(2);
        }
    },
    setIFrameFptId:function(id, type) {
        if ( type == 1 ) {
            var iframe  = '<iframe height="120" frameborder="0" width="382" scrolling="no" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" src="'+fptIdUrl+'/?display=iframe&referersp='+refererspC+'" id="if_idp" name="if_idp"></iframe>';
        } else if ( type == 2 ) {
            var iframe  = '<iframe height="120" frameborder="0" width="382" scrolling="no" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" src="'+fptIdUrl+'/?display=iframe&referersp='+refererspV+'" id="if_idp" name="if_idp"></iframe>';
        }
        $("#"+id).html(iframe);
    }
}

$(function(){
    /**
     * Auto slide
     */
    $("div.s2").CarouSlide({
        animType:"slide-vertical",
        autoAnim:false,
        slideTime:4000,
        animTime:800,
        alwaysNext:true
    });

    /**
     * Lightbox login
     */
    $("#hide").hide();

    /**
     * Widget
     */
    setTimeout("FPT_widget_mix();", 100);

    /**
     * Get comment
     */
    DetailArticle.getComment(1);
    
    /**
     * Banbe plugins like
     */
    if ( !$.browser.msie ) {
        FOConnect._TIME_REFRESH = 10;
        FOConnect.init({
            consumerkey: bb_plugins_consumerkey,
            receiver : location.host + '/xd_receiver.html',
            domain : location.host,
            logouturl : location.href,
            loginNodeId : 'btnLogin', // the ID of DOM node where FOC login button will display
            loginNodeText : 'Đăng nhập',
            logoutNodeText : 'Thoát',
            registerNodeId : 'btnRegister', // the ID of DOM node where FOC register a new account button will display
            autoSynSessionTimeout : 0,        //option params (auto syn session between banbe.net and third-party web app)
            autoSynSessionCallback : function(status){
                if(!status){
                    //TODO confirm user here
                    if (true) {
                        FOConnect.logout();
                        return true; //must return true if user confirmed logout this site
                    }
                }
                return false; //must return false as the default
            }
        });
    }
    
    /**
     * Init open id
     */
    openid.img_path = imgPath +'/icons/openid';
    openid.init('openid_identifier');
});

/**
 * Facebook plugin like
 */
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s);
    js.id = id;
    js.src = "//connect.facebook.net/vi_VN/all.js#xfbml=1";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

/**
 * Goggle + plugins
 */
window.___gcfg = {lang: 'vi'};
(function() {
    var po = document.createElement('script');
    po.type = 'text/javascript';
    po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(po, s);
})();

/**
 * Login callback
 */
window.loginCallback    = function(a, b){
    jQuery.colorbox.close();
    
    if ("function" == a) {
        eval('parent.' + b + "()");
    }
}

/**
 * Call comment
 */
function callComment()
{
    DetailArticle.redirect  = 1;
    DetailArticle.comment(3);
}

/**
 * Call vote
 */
function callVote()
{
    DetailArticle.redirect  = 1;
    DetailArticle.vote(articleId);
}